﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IceTea.Domain.Models;

namespace IceTea.Domain
{
    public class PBIFactory
    {
        /// <summary>
        /// Get the PBI list of a product or according to the PBI type
        /// the result is ordered by the priority
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IEnumerable<PBI> GetProductRootPBIs(int productId, short type = -1)
        {
            using (IceTeaEntities ite = new IceTeaEntities())
            {
                var results = (from pbi in ite.PBIs.Include("User").Include("User1") 
                               where pbi.ProductId == productId && pbi.ParentId.HasValue == false
                               select pbi);
                if (type >= 0)
                    results = (from pbi in results where pbi.Type == type select pbi);

                results = results.OrderBy(pbi => pbi.Priority);

                return results.ToList();
            }
        }

        /// <summary>
        /// Create new Product Backlog Item in DB
        /// </summary>
        /// <param name="pbi"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static long CreatePBI(PBI pbi, int userId)
        {
            using (IceTeaEntities ite = new IceTeaEntities())
            {
                pbi.CreatedBy = userId;
                pbi.CreatedTime = DateTime.Now;
                pbi.UpdatedBy = userId;
                pbi.UpdatedTime = DateTime.Now;

                ite.PBIs.AddObject(pbi);
                if (ite.SaveChanges() > 0)
                    return pbi.Id;

                return -1;
            }
        }
    }
}
